﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using RssReaderTemplate.Model;
using RssReaderTemplate.Repositories;
using Microsoft.Phone.Reactive;
using System.Linq;
using System.Runtime.Serialization;
using System.Collections.Generic;
using RssReaderTemplate.Globalization;

namespace RssReaderTemplate.ViewModels
{
    [DataContract]
    public class CategoriesViewModel : NetworkRequiredViewModel, IObserver<RssItem>
    {
        public CategoriesViewModel(RssRepository repository)
        {
            repository.ObserveOnDispatcher().Subscribe(this);
            _categories = new ObservableCollection<CategoryViewModel>();
        }

        private int _currentCategory;
        [IgnoreDataMember]
        public int CurrentCategory
        {
            get { return _currentCategory; }
            set
            {
                _currentCategory = value; OnPropertyChanged("CurrentCategory");
            }
        }


        private ObservableCollection<CategoryViewModel> _categories;
        [DataMember]
        public ObservableCollection<CategoryViewModel> Categories
        {
            get { return _categories; }
            set { _categories = value; }
        }

        private IList<RssItem> _items = new List<RssItem>();

        [DataMember]
        public IList<RssItem> Items
        {
            get { return _items; }
            set { _items = value; }
        }


        public void OnCompleted()
        {
        }

        public void OnError(Exception exception)
        {
        }

        public void OnNext(RssItem value)
        {
            if (Items.Count + Categories.Count + value.Categories.Count == 0)
            {
                Categories.Add(new CategoryViewModel(AppResources.Uncategorized));
            }
            _items.Add(value);
            if (value.Categories.Count == 0)
            {
                _categories.Single(x => x.Name == AppResources.Uncategorized).Elements.Add(value);
            }
            else
            {
                foreach (var category in value.Categories)
                {
                    CategoryViewModel vm = Categories.SingleOrDefault(x => x.Name == category);
                    if (vm == null)
                    {
                        vm = new CategoryViewModel(category);
                        Categories.Add(vm);
                    }
                    vm.Elements.Add(value);
                }
            }
        }
    }
}
